package com.mcintyret.site.service.journal;

import com.mcintyret.site.journal.Journal;
import com.mcintyret.site.journal.TextEntry;
import com.mcintyret.site.journal.database.JournalDao;
import com.mcintyret.site.journal.database.TextEntryDao;
import com.mcintyret.site.web.controller.journal.forms.TextEntryForm;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * User: mcintyret2
 * Date: 13/04/2012
 */

@Service
public class TextEntryHelper {

    @Resource
    private JournalDao journalDao;
    @Resource
    private TextEntryDao textEntryDao;


    public void deleteTextEntryWithId(int id) {
        TextEntry textEntry = textEntryDao.get(id);
        textEntry.getJournal().getTextEntries().remove(textEntry);
    }

    public Integer addNewTextEntryToJournal(TextEntryForm form) {
        TextEntry newTextEntry = createTextEntryFromForm(form);
        Journal journal = journalDao.get(form.getJournalId());
        journal.addTextEntry(newTextEntry);
        journalDao.flushSession();
        return newTextEntry.getId();
    }

    private TextEntry createTextEntryFromForm(TextEntryForm form) {
        TextEntry textEntry = new TextEntry(form.getContent());
        if (form.getDatetime() != null) {
            textEntry.setTime(form.getDatetime());
        }
        return textEntry;
    }


}
